<template>
  <div>
    <el-form ref="formSearch"
             :model="formSearch"
             label-width="100px"
             size="small"
             :inline="true">
      <el-form-item>
        <el-button type="primary"
                   size="small"
                   @click.stop="handleAdd()">添加</el-button>
      </el-form-item>
      <!--<el-form-item label="角色状态:">
        <el-select v-model="formSearch.stutas"
                   placeholder="账户状态"
                   style="width:100px">
          <el-option label="全部"
                     :value="0"></el-option>
          <el-option label="已启用"
                     :value="1"></el-option>
          <el-option label="已禁用"
                     :value="2"></el-option>
        </el-select>
      </el-form-item>-->
      <el-form-item label="角色名称:">
        <el-input v-model="formSearch.name"
                  placeholder="请输入角色名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   @click="searchFormSubmit()">搜索</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <avue-crud :option="tableOption"
               :data="tableData"
               :table-loading="tableLoading"
               :page="page"
               ref="crud"
               @size-change='sizeChange'
               @current-change='currentPage'>
      <!-- <template slot-scope="scope" slot="status">
            {{scope.row.status==1?'未留样':'已留样'}}
        </template> -->
      <template slot-scope="scope"
                slot="editTime">
        {{scope.row.name}}<span>-</span>{{scope.row.state}}
      </template>
      <template slot-scope="scope"
                slot="menu">
        <el-button type="primary"
                   size="small"
                   plain
                   @click.stop="handleEdit(scope.row,scope.index)">修改</el-button>
        <el-button type="primary"
                   size="small"
                   plain
                   @click.stop="handleDelete(scope.row,scope.index)">删除</el-button>
      </template>
    </avue-crud>
    <!-- 添加/修改样品 -->
    <el-dialog :title="dialogTitle"
               :visible.sync="dialogFormVisible"
               width="40%"
               class="diading">
      <el-form ref="dialogForm"
               :model="dialogForm"
               :rules="rules"
               label-position="left"
               label-width="100px"
               class='role-form'>
        <el-form-item label="角色名称"
                      prop='name'>
          <el-input v-model="dialogForm.name"
                    placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="权限设置"
                      prop='role'>
          <el-tree :data="treeData"
                   show-checkbox
                   default-expand-all
                   node-key="id"
                   ref="tree"
                   highlight-current
                   :props="defaultProps"
                   @check-change='changeTree'></el-tree>
        </el-form-item>
        <!--<el-form-item label="状态："
                      prop='status'>
          <el-radio-group v-model="dialogForm.status">
            <el-radio label="启用"
                      :value='0'></el-radio>
            <el-radio label="禁用"
                      :value='1'></el-radio>
          </el-radio-group>
        </el-form-item>-->
      </el-form>
      <div slot="footer"
           class="dialog-footer"
           style="text-align:center">
        <el-button @click="dialogFormVisible = false">关 闭</el-button>
        <el-button type="primary"
                   @click="handleAddLine('dialogForm')">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { roleListOption } from "@/const-personal/sysSetup/user.js"
import { getUserByRolesList, deleteRolesItem, getUserByRolesType, updateUserByRoles, addUserByRoles } from "@/api/sysSetup/uesr.js";
import { validatenull } from '@/util/validate'
import { RestructureMenu ,DepartmentTree} from '@/util/util'
import { getMenuAll ,getMenuById } from "@/api/public/menu.js";


export default {
  name: "roleList",
  data () {
    return {
      formSearch: {
        name: "",
        stutas: 0
      },
      tableOption: roleListOption,
      page: {
        total: 10, //总页数
        currentPage: 1, //当前页数
        pageSize: 10, //每页显示多少条
        pageSizes: [5, 10, 20]
      },
      tableLoading: false,
      tableData: [{ id: 0, status: 2 }, { id: 2, status: 1 }],//数据
      // 新增修改
      dialogTitle: '添加角色',
      dialogFormVisible: false,
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        role: [{ required: true, message: '请选择权限设置', trigger: 'change', type: 'array' }],
        // status: [{ required: true, message: '请选择角色状态', trigger: 'change' }]
      },
      dialogForm: {
          name:'',
          role: []
      },
      treeData: [],
      // 多级联动配置
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  created(){
        // this.getMenuAllData();
  },
  mounted () {
    this._getRolesList()
  },
  methods: {
    //获取角色列表
    _getRolesList (search) {
      let data = {
        page: this.page.currentPage,
        size: this.page.pageSize,
        name: this.formSearch.name
      };
      if (search) {
        data['page'] = 1
      }
      getUserByRolesList(data).then(res => {
        if (res.data.code === 200) {
          this.tableData = res.data.data.list;
          this.page.total = res.data.data.total;
          this.page.pageSize = res.data.data.pageSize
          this.page.currentPage = res.data.data.pageNum
        }
      })
    },
    // 搜索
    searchFormSubmit () {
      console.log(this.formSearch)
      this._getRolesList(this.formSearch)
      // this.formSearch = {}
    },
    // 切换页面
    currentPage (val) {
      this.page.currentPage = val
      this._getRolesList()
    },
    sizeChange (val) {
      this.page.pageSize = val
      this._getRolesList()
    },
    // 新增
    handleAdd () {
      getMenuAll().then(res=>{
          if (res.data.code === 200) {
              this.treeData = []
              res.data.data.forEach(itme=>{
                  if(validatenull(itme.parentId)){
                      this.treeData.push(itme)
                  }
              })
              this.treeData = DepartmentTree(this.treeData)
          }
      })
      this.dialogFormVisible = true;
      this.dialogTitle = '添加角色';
      this.dialogForm = {
        name: '',
        status: ''
      }
    },
    getMenuAllData(id){
        this.handleAdd()
        getMenuById({id: id}).then(res => {
            if (res.data.code === 200) {
                this.$refs.tree.setCheckedNodes(this.MenuData(res.data.data));
            } else {
                this.$notify.error({ title: '查询失败', message: res.data.message, type: 'danger' });
            }
        })
    },
    MenuData(menu){
        let data = []
        menu.reverse().forEach(item=>{
            if(item.flog == 0 && item.grade == 3){
                data.push({
                    id:  item.id,
                    label: item.name,
                })
            }
        })
        /*menu.forEach(item=>{
            if(validatenull(item.parentId)&&item.flog == 0){
                data.push({
                    id:  item.id,
                    label: item.name,
                    children:[]
                })
            }
        })
        data.forEach(item=>{
            menu.forEach(items=>{
                if(item.id == items.parentId&&items.flog == 0){
                    item.children.push({
                        id:  items.id,
                        label: items.name,
                        children:[]
                    })
                }
            })
        })
        data.forEach(item=>{
            item.children.forEach(items=>{
                menu.forEach(m=>{
                    if(items.id == m.parentId&&m.flog ==0){
                        items.children.push({
                            id:  m.id,
                            label: m.name,
                        })
                    }
                })
            })
        })*/
        return data
    },
    // 修改
    handleEdit (row, index) {
      this.dialogFormVisible = true;
      this.dialogTitle = '修改角色';
      this.getMenuAllData(row.id);
      this.dialogForm.name = row.name;
      this.dialogForm.id = row.id
    },
    // 删除
    handleDelete (row, index) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        //请求--删除
        deleteRolesItem({ id: row.id }).then(res => {
          if (res.data.code === 200) {
            this._getRolesList()
            this.$notify({ title: '操作成功', type: 'success', message: '已成功删除（'+this.dialogForm.name+'）!'});
          } else {
            this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger', });
          }
        })
      });
    },
    // 确认新增/修改
    handleAddLine (formName) {
      this.dialogForm.role = []
      this.$refs.tree.getCheckedNodes().forEach(item=>{
          this.dialogForm.role.push({ id: item.id,name: item.label })
      })
      this.$refs[formName].validate((valid) => {
        if (valid) {
            if(validatenull(this.dialogForm.id)){
                addUserByRoles({
                    name : this.dialogForm.name,
                    menus : this.dialogForm.role
                }).then(res => {
                    if (res.data.code === 200) {
                        this.$notify({ title: '操作成功', type: 'success', message: '添加成功!'});
                        this._getRolesList()
                        this.dialogFormVisible = false;
                        this.$refs[formName].resetFields();
                    } else {
                        this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger' });
                    }
                })
            } else {
                updateUserByRoles({
                    name : this.dialogForm.name,
                    menus : this.dialogForm.role,
                    id : this.dialogForm.id,
                }).then(res => {
                    if (res.data.code === 200) {
                        this.$notify({ title: '操作成功', type: 'success', message: '修改成功!'});
                        this._getRolesList()
                        this.dialogFormVisible = false;
                        this.$refs[formName].resetFields();
                    } else {
                        this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger' });
                    }
                })
            }
        }
      })
    },
    // 选中权限
    changeTree (value) {
     /* this.dialogForm.role = this.$refs.tree.getCheckedKeys()
      console.log(this.treeData)
      console.log(this.$refs.tree.getCheckedNodes());
      console.log(this.$refs.tree.getCheckedKeys())*/
    }
  }
};
</script>

<style>
.role-form {
  max-height: 340px;
  overflow-y: auto;
}
.role-form .el-tree-node__content > label.el-checkbox {
  position: absolute;
  right: 0;
}
</style>